package lwk.thread.demo;



public class Race implements Runnable {

    //胜利者
    private static String winner;
    private static final int tzSpeed = 4; // 兔子速度
    private static final int wgSpeed = 1; // 乌龟速度
    private static final int zhongDain = 1000; // 终点距离

    @Override
    public void run() {


        if (Thread.currentThread().getName().equals("兔子")) {

            for (int i = 0; i <= zhongDain / tzSpeed; i++) {
                if (i == 25) {
                    System.out.println("兔子开始睡觉了....");
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("兔子终于睡醒了....");
                }
                //判断比赛是否结束
                boolean flag = gameOver(i * tzSpeed);
                //如果比赛结束了，就停止程序
                if (flag) {
                    break;
                }
                System.out.println(Thread.currentThread().getName() + "-->跑了" + i * tzSpeed + "步");

            }
        } else {
            for (int i = 0; i <= zhongDain / wgSpeed; i++) {
                //判断比赛是否结束
                boolean flag = gameOver(i * wgSpeed);
                //如果比赛结束了，就停止程序
                if (flag) {
                    break;
                }
                System.out.println(Thread.currentThread().getName() + "-->跑了" + i * wgSpeed + "步");
            }
        }
    }

    //判断是否完成比赛
    private boolean gameOver(int steps) {
        if (winner != null) {//已经有胜利者了
            return true;
        } else {
            if (steps >= zhongDain) {
                winner = Thread.currentThread().getName();
                System.out.println("Winner is " + winner);
                return true;
            }

        }
        return false;
    }

    public static void main(String[] args) {

        Race race = new Race();
        new Thread(race, "乌龟").start();
        new Thread(race, "兔子").start();

    }

}